<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
	
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.Iterator" %>
<%@page import="com.easyattendance.services.AddSectionService"%>
<%@ page import ="com.easyattendance.services.AddClassService" %>
<%@ page import ="com.easyattendance.model.Class" %>
<%@ page import ="com.easyattendance.services.AddTeacherService" %>
<%@ page import ="com.easyattendance.model.Teacher" %>
<%@ page import ="com.easyattendance.model.Subject" %>
<%@ page import="com.easyattendance.services.AddAllTimeSlotsService"%>
<%@ page import ="com.easyattendance.model.AllTimeSlots"%>
<%@ page import ="com.easyattendance.model.TimeTable"%>
<%@ page import ="com.easyattendance.services.AddProxyService" %>
<%@ page import ="com.easyattendance.services.AddSubjectService" %>
<%@ page import="java.util.Date" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Section - Settings</title>
<!-- <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> -->
<jsp:include page="../includeFiles.jsp" ></jsp:include>

<script src="<%=request.getContextPath()%>/public/js/tabbed_pages.js" type="text/javascript"></script>

<!-- DatePicker Style & Scripts -->
<link rel="stylesheet" href="<%=request.getContextPath()%>/views/css/ui/jquery-ui-1.10.4.custom.min.css">
<script src="<%=request.getContextPath()%>/public/js/ui/jquery.ui.core.js"></script>
<script src="<%=request.getContextPath()%>/public/js/ui/jquery.ui.widget.js"></script>
<script src="<%=request.getContextPath()%>/public/js/ui/jquery.ui.datepicker.js"></script>
<script>
	/* $(function() {
		$( "#proxy_dt" ).datepicker({ dateFormat: "yy-mm-dd" }).val();
	}); */
	$(function() {
	    $('#proxy_dt').datepicker( {
	    	'dateFormat':'yy-mm-dd',
	    	beforeShowDay: noSunday,
	        onSelect: function(dateText, inst) {
	        	var date = $(this).datepicker('getDate');
	        	var day = $.datepicker.formatDate('DD', date);
	        	var proxy_date = $.datepicker.formatDate('yy-mm-dd', date);
		        //console.log(day);
		        $("#days_select").val(day);
		        setCookie("days_select",day);
		        setCookie("proxy_date",proxy_date);
	        }
	    });
	});
	function noSunday(date){ 
        return [date.getDay() != 0, ''];
     };
</script>
<!-- Ends : DatePicker Style & Scripts -->

</head>

<body class="left-sidebar">

<!-- Session check : user logged in or not/ press back button -->
<jsp:include page="../common/checkSession.jsp"></jsp:include>
<jsp:include page="../common/checkSectionRole.jsp" />

<% String currentUser = (String) session.getAttribute("currentUser"); %>

	<!-- Wrapper -->
	<div id="wrapper">

		<!-- Content -->
		<div id="content">
			<div id="content-inner">
				<div id="gallery">
					<div class="on" id="tab_proxy" title="Proxy"><span>Proxy</span></div>
					<div class="off" id="tab_general" title="General"><span>General</span></div>
					<div class="off" id="tab_password" title="Password"><span>Password</span></div>										
				</div>	
				
				<!-- ************************************************************************************* -->
				<!-- Proxy Settings Starts Here -->
				<div id="Proxy" class="show">
					<div id="login_content">
						<header>
							<h2>Add Proxy</h2>
						</header>
						
						<span class="error_msg">${proxyExists}</span>
						<span class="success_msg">${proxyAdded}</span>
						<span class="error_msg">${proxyNotAdded}</span>
						<div class="submit_errors_msg">
							<ul>
								<li id="submit_is_field_empty" class="submit_errors">All * fields are required. You must select at least 1 from drop-down.</li>
							</ul>
						</div>
						<form name="addProxyFrom" action="${pageContext.request.contextPath}/AddProxyServlet" method="post" onsubmit="return checkProxyErrors()">
							<!--Date -->
							<div>
								<label>Date:</label>
								<input id="proxy_dt" name="proxy_dt" type="text" placeholder="Date" value="" tabindex="1">
							</div>
							
							<!-- Day of Week -->
							<div>
								<label>Day of Week:</label>
								<input id="days_select" name="days_select" type="text" placeholder="Day" value="" tabindex="2" readonly="readonly">
							</div>
							
							
							
							<!-- Time Slot of Day-->
							<div>
							<% AddAllTimeSlotsService service = new AddAllTimeSlotsService();
							AddSectionService deptService = new AddSectionService();
							String deptId = deptService.getSectionBySectionEmail(currentUser).getSection_id();
							String[] timeSlots = service.listAllTimeSlotsBySection(currentUser);
							%>
								<label>Select Time Slot:</label>
								<select name="timeslot_select" id="timeslot_select" tabindex="3" value=<script>getCookie("timeslot_select")</script>>
								<option value="">Choose Time Slot
									<%for(int i=0; i<timeSlots.length; i++ ){ %>
										<option value='<%=timeSlots[i]%>'><%=timeSlots[i]%>
									<% } %>
									
								</select>
							</div>
							
							<!-- Choose Sem Year for which proxy is to b added-->
							<div>
								<label>Choose Class:</label>
								<select name="class_select" id="class_select" tabindex="4" value=<script>getCookie("class_select")</script> >
									<option value="">Select Class
										<% AddClassService addClassService = new AddClassService();	
										List<Class> ClassList = new ArrayList<Class>();
										ClassList = addClassService.listClasses(currentUser);
										Class tempClass = null;
										Iterator ClassItr = ClassList.iterator();
								
										while(ClassItr.hasNext()) { %>
											<% tempClass = (Class) ClassItr.next();
												String ClassName = tempClass.getClass_name();
												String ClassId = tempClass.getClass_id();%>
									<option value='<%=ClassId%>'><%= ClassName %>
									<% } %>
								</select>
							</div>
							
							<!-- Lecture of which teacher??? -->
							
							<%  AddTeacherService teacherService = new AddTeacherService();
								String ClassId = request.getParameter("Class");
								String day = request.getParameter("day");
								String timeSlot = request.getParameter("timeSlot");
								TimeTable timeTable = null;
								Teacher subjectTeacher =null;
								Subject subject = null;
							%>
								<% System.out.println("ClassID JSP: "+ClassId);
								if(ClassId != null) {
								%>
									<% timeTable = teacherService.listTimeTableOnDayForTimeSlot(day, timeSlot, ClassId);
									if(timeTable == null) {%>
										<div>
											<label> No leture alloted to this timeslot </label>
										</div>
									<% } else { %>
										<div>
											<label> Teacher currently alloted to this timeslot: <%=timeTable.getTeacher().getTeacher_name()%>&nbsp;<%=timeTable.getTeacher().getTeacher_lname()%> </label>
										</div>
										
										<div>
											<label> Subject currently alloted to this timeslot: <%=timeTable.getSubject().getSubject_name()%></label>
										</div>
									<%} %>
								<% } else { %>
										<div>
											<label> Select above details to get the teacher </label>
										</div>
									<%} %>
							
							<input name="day_selected" id="day_selected" type="hidden" value=<%=day%>>
							<input name="timeslot_selected" id="timeslot_selected" type="hidden" value=<%=timeSlot%>>
							
							
							<!-- Proxy TEacher -->
							<% if(timeTable != null) { %>
							<div>
								<label>Choose Proxy Teacher:</label>
								<select name="proxy_teacher_select" id="proxy_teacher_select" tabindex="5">
									<option value="">Choose Proxy Teacher
										<% AddTeacherService addTeacherService = new AddTeacherService();	
											List<Teacher> teacherList = new ArrayList<Teacher>();
											teacherList = addTeacherService.listTeachers(currentUser, timeTable.getTeacher().getTeacher_id());
											Teacher tempTeacher = null; 
											
											Iterator teacherItr = teacherList.iterator();
									
											while(teacherItr.hasNext()) { %>
												<% tempTeacher = (Teacher) teacherItr.next();
													String teacherName = tempTeacher.getTeacher_name();
													String teacherId = tempTeacher.getTeacher_id(); %>
													<option value='<%=teacherId%>'><%= teacherName %>
											<% } %>
								</select>
							</div>		
							<input type="hidden" name="subject_teacher_id" id="subject_teacher_id" value=<%=timeTable.getTeacher().getTeacher_id()%>>
							<input type="hidden" name="subject_id" id="subject_id" value=<%=timeTable.getSubject_id()%>>
							<% } %>			
								
							<!--Choose Subject of Proxy Teacher -->
							
							<% String proxyTeacher = request.getParameter("proxyTeacher"); %>	
							
							<% if(proxyTeacher != null && ClassId != null && timeTable!=null) { %>
								<div>
									<label>Choose Subject of Proxy Teacher:</label>
									<select name="subject_select" id="subject_select" tabindex="6">
										<option value="">Choose Subject of Proxy Teacher
											<% AddSubjectService addSubjectService = new AddSubjectService();	
											List subjectList = new ArrayList();
											subjectList = addSubjectService.listSubjectsByTeacherId(proxyTeacher, ClassId);
											Subject tempSubject = null;
											Iterator subjectItr = subjectList.iterator();
									
											while(subjectItr.hasNext()) { %>
												<% tempSubject = (Subject) subjectItr.next();
													String subjectName = tempSubject.getSubject_name();
													String subjectId = tempSubject.getSubject_id(); %>
										<option value='<%=subjectId%>'><%=subjectName%>
										<% } %>
									</select>
								</div>
							<% }%>
							
							<input type="hidden" name="class_selected" id="class_selected" value=<%=ClassId%>>
							<input type="hidden" name="proxy_teacher_name" id="proxy_teacher_name" value=<%=proxyTeacher%>>
							<input type="hidden" name="section_id" id="section_id" value=<%=deptId%>>
							
							<div>	
								<center><input type="submit" value="Save" class="button" tabindex="7" style="width: 50%;"></center>
							</div>
						</form>
					</div>
				</div>
				<!-- Proxy Settings End Here -->
				
				<!-- ******************************************************************************************* -->
				
				<!-- ******************************************************************************************* -->
				<!-- General Settings Starts Here -->
				<div id="General" class="hide">
					<div id="login_content">
						<header>
							<h2>Email Settings</h2>
						</header>
						<span class="error_msg">${email_null_values}</span>
						<span class="success_msg">${email_added}</span>
						<span class="error_msg">${email_not_added}</span>
						<span class="error_msg">${email_exists}</span>
						<div class="submit_errors_msg">
							<ul>
								<li id="submit_general_field_empty" class="submit_errors">All * fields are required. You must select at least 1 from drop-down.</li>
							</ul>
						</div>
						<form name="" method="post" action="${pageContext.request.contextPath}/EmailServlet" onsubmit="return checkGeneralErrors()">
							<!-- Email message format -->
							<div>
								<label>Email Message Template:</label>
								<textarea id="email_template" name="email_template" type="textarea" placeholder="Email Message Template"  rows="3" tabindex="1" style="resize: none;"></textarea>
							</div>
							<!-- Gmail -->
							<div>
								<label>Gmail ID:</label>
								<input id="gmail_id"  name="gmail_id" type="text" placeholder="Email ID" maxlength="32" tabindex="2">
							</div>
							<!-- Email Validation error and success message area. -->
							<div id="email_error" class="error_info">
								<ul>
									<li id="email_empty" class="invalid">Email address cannot be empty.</li>
									<li id="email_invalid" class="invalid">Valid email address?</li>
								</ul>
							</div>
							<div>
								<label>Gmail Password:</label> 
								<input id="gmail_password" name="gmail_password" type="password" placeholder="Password" tabindex="3">
							</div>
													
							<div>	
								<center><input type="submit" value="Save" class="button" tabindex="4" style="width: 50%;"></center>
							</div>
						</form>
					</div>	
				</div>
				<!-- General Settings End Here -->
				
				<!-- ******************************************************************************************* -->
				
				<!-- Change Password Starts Here -->
				<div id="Password" class="hide">
					<div id="login_content">
						<header>
							<h2>Change Password</h2>
						</header>
						
							<span class="error_msg">${errorMessage}</span>
							<span class="success_msg">${successMessage}</span>
						
						<form name="changeDeptPasswordForm" action="${pageContext.request.contextPath}/ChangePasswordServlet" method="post" onsubmit="return checkPasswordErrors()">
							<!-- Enter Email ID -->
							<!-- <div>
								<label>Email - ID:</label> 
								<input id="email" type="email" placeholder="Email ID" maxlength="50" tabindex="1" name="email">
								<!-- Compared to stored password using Ajax or Server side Script 
							</div> -->
							<!-- Email Validation error and success message area. -->
							<!-- <div id="email_error" class="error_info">
								<ul>
									<li id="email_empty" class="invalid">Email address cannot be empty.</li>
									<li id="email_invalid" class="invalid">Valid email address?</li>
								</ul>
							</div>  -->
							
							<!-- Enter old Password -->
							<div>
								<label>Old Password:</label> 
								<input type="password" placeholder="Old Password" maxlength="32" tabindex="1" name="oldpassword">
								<!-- Compared to stored password using Ajax or Server side Script -->
							</div>
							<!-- Enter new Password -->
							<div>
								<label>New Password:</label> 
								<input id="dept_new_password" type="password" placeholder="New Password" maxlength="32" tabindex="2" name="newpassword">
							</div>
							<!-- Password Validation error and success message area. -->
							<div id="pass_error" class="error_info">
								<ul>
									<li id="letter" class="invalid">At least <strong>one letter</strong></li>
									<li id="capital" class="invalid">At least <strong>one capital letter</strong></li>
									<li id="number" class="invalid">At least <strong>one number</strong></li>
									<li id="length" class="invalid">Be at least <strong>8 characters</strong></li>
									<li id="character" class="invalid">At least <strong>one special character</strong></li>
								</ul>
							</div>
							<!-- Re-enter new Password -->
							<div>
								<label>Confirm Password:</label> 
								<input id="dept_new_repassword" type="password" placeholder="Re-enter Password" maxlength="32" tabindex="3" name="new_repassword">
							</div>
							<!-- Compare Passwords. -->
							<div id="compare_pass_error" class="error_info">
								<ul>
									<li id="compare_pass" class="invalid">Passwords must be similar & non-empty.</li>
								</ul>
							</div>	
							<!-- Hidden field -->
								<input type="hidden" name="email" id="email" value="<%=currentUser %>">
														
							<div>	
								<input type="submit" value="Change" class="button" tabindex="4">
							</div>
						</form>
					</div>	
				</div>
				<!--<input type="button" value="Delete Cookies" class="button" onclick="clearCookie()">   -->
				<!-- Change Password End Here -->
				
				<!-- ******************************************************************************************* -->
				
				
				
			</div>
		</div>

		<!-- Sidebar -->
		<div id="sidebar">

			<!-- Sidebar Header - Logo & Name -->
			<jsp:include page="../common/sidebarHeader.jsp" ></jsp:include>

			<jsp:include page="sectionMenu.jsp" />
							
			<!-- Sidebar Footer Content -->
			<jsp:include page="../common/sidebarFooter.jsp" />

		</div>

	</div>
	<script type="text/javascript">
		$(function(){
			$("#generalSettings").addClass("current_page_item");
		});
		var contextPath='<%=request.getContextPath()%>';
	</script>
	
	<script type="text/javascript">
	
		//Get Cookie values by calling this function
		$(function() {
			getValues();
		});
	
		/* General Settings */
		$("#gmail_id").keyup(function() {
			isEmailValid($("#gmail_id"));
		});
		$("#gmail_password").keyup(function() {
			isPasswordValid($("#gmail_password"));
		});
		
		/* Change Password */
		$("#dept_new_password").keyup(function() {
			isPasswordValid($("#dept_new_password"));
		});
		$("#dept_new_repassword").keyup(function() {
			isPasswordSame($("#dept_new_password"),$("#dept_new_repassword"));
		});
								
		// To get timeslot and day selected and populate subjects in subj drop down
		$("#timeslot_select").change(function() {
			var timeslot = $("#timeslot_select").val();
			setCookie("timeslot_select",timeslot);
		});
		
		// Get Dropdown list values
		
		//If selected class changes.
		$(function () {
		    var temp = 0;
		    $('#class_select').click(function () {        
		    	temp++;
		        if (temp == 2) {
		            $(this).change();
		            temp = 0;
		        }         
		    }).change (function () {
		    	var day = $("#days_select").val();
				var timeslot = $("#timeslot_select").val();
				var classs = $("#class_select").val();
				var proxy_date = $("#proxy_dt").val();
				setCookie("class_select",classs);
				setCookie("proxy_date",proxy_date);
				window.location.replace(contextPath + "/views/section/generalSettings.jsp?proxyDate="+ proxy_date + "&day=" + day + "&timeSlot=" + timeslot + "&Class="+classs);
		    });      
		});

		//If selected proxy teacher changes.
		$(function () {
		    var temp = 0;
		    $('#proxy_teacher_select').click(function () {        
		    	temp++;
		        if (temp == 2) {
		            $(this).change();
		            temp = 0;
		        }         
		    }).change (function () {
		    	var day = $("#days_select").val();
				var timeslot = $("#timeslot_select").val();
				var classs = $("#class_select").val();
				var proxy_teacher_name = $("#proxy_teacher_select").val();
				var proxy_date = $("#proxy_dt").val();
				setCookie("days_select",day);
				setCookie("timeslot_select",timeslot);
				setCookie("proxy_teacher_select",proxy_teacher_name);
				setCookie("class_select",classs);
				setCookie("proxy_date",proxy_date);
				window.location.replace(contextPath + "/views/section/generalSettings.jsp?proxyDate="+ proxy_date + "&day=" + day + "&timeSlot=" + timeslot + "&Class="+classs +"&proxyTeacher="+proxy_teacher_name);
		    });      
		});
		
		function setCookie(name, value) {
			  var today = new Date(); 
			  var expiry = new Date(today.getTime() + 1 * 24 * 3600 * 1000);
			  document.cookie=name + "=" + escape(value) + "; path=/; expires=" + expiry.toGMTString();
		 }
			 
		function getCookie(name) { 
			var re = new RegExp(name + "=([^;]+)"); 
			var value = re.exec(document.cookie);
			return (value != null) ? unescape(value[1]) : null; 
		}
		
		function getValues(){
			$("#days_select").val(getCookie("days_select"));
			//$("#days_select").text(getCookie("days_select"));
			$("#timeslot_select").val(getCookie("timeslot_select"));
			$("#class_select").val(getCookie("class_select"));
			$("#proxy_teacher_select").val(getCookie("proxy_teacher_select"));
			$("#proxy_dt").val(getCookie("proxy_date"));
		}
		
		function deleteCookie(name) {
			var today = new Date(); 
			var expired = new Date(today.getTime() - 24 * 3600 * 1000); // less 24 hours
			document.cookie=name + "=null; path=/; expires=" + expired.toGMTString();
		}
		
		function clearCookie(){
			deleteCookie("proxy_date");
			deleteCookie("days_select");
			deleteCookie("timeslot_select");
			deleteCookie("class_select");
			deleteCookie("proxy_teacher_select");
			alert("Cookies Deleted");
		}
		
		$("#subject_select").change(function(){
			var subject_name = $("#subject_select").val();
			$('#proxy_subject_name').attr("value",subject_name);
		});
		
	</script>
	<script>
	$(".submit_errors_msg").hide();
	$(".submit_errors").hide();
	
	function checkProxyErrors(){
		/* if(isAnyFieldEmpty($('#proxy_dt'),$('#days_select'),$('#timeslot_select'),$('#class_select'),$('#proxy_teacher_select'),$('#subject_select'))){
			return true;
		}else{
			$('#submit_general_field_empty').hide();
			$('#submit_is_field_empty').show();
			$('#submit_password_field_empty').hide();
			return false;	
		} */
	}
	function checkGeneralErrors(){
		/* if(isAnyFieldEmpty($('#email_template'),$('#gmail_id'),$('#gmail_password'))){
			return true;
		}else{
			$('#submit_general_field_empty').show();
			$('#submit_is_field_empty').hide();
			$('#submit_password_field_empty').hide();
			return false;	
		} */
	}
	function checkPasswordErrors(){
		/* if(isAnyFieldEmpty($('#proxy_dt'),$('#days_select'),$('#timeslot_select'),$('#class_select'),$('#proxy_teacher_select'),$('#subject_select'))){
			return true;
		}else{
			$('#submit_general_field_empty').hide();
			$('#submit_is_field_empty').hide();
			$('#submit_password_field_empty').show();
			return false;	
		} */
	}
	</script>
</body>
</html>